from fileinput import close
import pymysql

def buildDbHelper(host='106.52.100.112',port=33306,user='cp',passwd='mysql',database='cp', openDb=True):
    return dbHelper(host, port, user, passwd, database, openDb)

class dbHelper():

    host = '192.168.31.21'
    port = 3306
    user = 'root'
    passwd = 'root123'
    database = 'dcms_ps'
    db = None

    def __enter__(self):
        return self
    def __exit__(self, exceptionType, exceptionVal, trace):
        close()
            

    def __init__(self, host, port, user, passwd, database, openDb=True):
        self.host = host
        self.port = port
        self.user = user
        self.passwd = passwd
        self.database = database
        if(openDb):
            self.connection()

    def connection(self):
        try:
            self.db = pymysql.connect(host=self.host,port= self.port,user= self.user,passwd= self.passwd,database=self.database)
        except Exception as e:
            self.db = None
            print('打开数据库连接异常', e)

    def close(self):
        try:
            self.db.close()
        except Exception as e:
            print('关闭数据库连接失败', e)

    def executeQuerySql(self, sql=''):
        cursor = None
        try:
            if sql and self.db:
                cursor = self.db.cursor()
                cursor.execute(sql)
                records = cursor.fetchall()
                return records
        except pymysql.Error as e:
            error = 'MySQL execute query failed! ERROR (%s): %s' % (
                e.args[0], e.args[1])
            print(error)
        finally:
            if cursor:
                cursor.close()

    def executeCommit(self, sql=''):
        cursor = None
        try:
            if sql and self.db:
                cursor = self.db.cursor()
                cursor.execute(sql)
                self.db.commit()
        except Exception as e:
            self.db.rollback()
            error = 'SQL execute failed! ERROR (%s): %s' % (
                e.args[0], e.args[1])
            print("error:", error)
        finally:
            if cursor:
                cursor.close()
